/******************************************************
 Project:				PCSync
 Author:				jean-philippe
 File name:				WatcherThread.java
 Date created:			Aug 21, 2012
 Date last modified:	Aug 21, 2012
 *******************************************************
 Modification History
 *******************************************************
 Aug 21, 2012		Initial version.
 ******************************************************/
package pcsync.client;

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import pcsync.Config;

/**
 * @author jean-philippe
 *  
 */
public class WatcherThread implements Runnable
{
	private WatchService watcher;
	private Logger logger;
	private ArrayList<Path> paths;
	
	public WatcherThread()
	{
		this.logger = Logger.getLogger(this.getClass().getCanonicalName());
		this.paths = new ArrayList<Path>();
		
		try
		{
			this.watcher = FileSystems.getDefault().newWatchService();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public boolean add(Path path)
	{
		try
		{
			path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
			this.paths.add(path);
		}
		catch (IOException e)
		{
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	
	@Override
	public void run()
	{
		this.logger.info("Watcher thread started (watching " + this.paths.size() + " directories)");
		
		while(true)
		{
			WatchKey key;
			
			try
			{
				key = watcher.poll(); // take, poll or timed-poll can be used.
				
				if( key != null )
				{
					List<WatchEvent<?>> events = key.pollEvents();
					for (WatchEvent<?> event : events)
					{
						if (event.kind() == ENTRY_MODIFY)
						{
							// consume the event
						}
						logger.info(event.kind().toString() + " : " + event.context().toString());
					}
					key.reset();
				}
				
				//logger.debug("Sleeping for " + POLL_INTERVAL + " ms");
				Thread.sleep(Config.POLL_INTERVAL);
			}
			catch (InterruptedException e)
			{
				logger.error("Thread interruption occured");
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		Path path = (new File("test")).toPath();
		
		WatcherThread wt = new WatcherThread();
		wt.add(path);
		(new Thread(wt)).start();
	}
}
